package com.cdut.hwadeefsc.controller;

import com.cdut.hwadeefsc.service.articlesService;
import com.cdut.hwadeefsc.entity.articles;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/articles")
public class articlesController {

    @Resource
    private articlesService articlesService;

    /**
     * 发布新闻、通知、公告
     */
    @PostMapping("/post")
    public ResponseEntity<?> postArticle(@RequestBody articles article) {
        try {
            // 验证必要字段
            if (article.getTitle() == null || article.getTitle().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("标题不能为空"));
            }
            if (article.getContent() == null || article.getContent().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("内容不能为空"));
            }
            if (article.getAuthorId() == null) {
                return ResponseEntity.badRequest().body(createErrorResponse("发布者ID不能为空"));
            }
            if (article.getType() == null) {
                return ResponseEntity.badRequest().body(createErrorResponse("信息类型不能为空"));
            }

            // 设置默认值和时间
            LocalDate now = LocalDate.now();
            article.setCreatedAt(now);
            article.setUpdatedAt(now);
            if (article.getIsPinned() == null) {
                article.setIsPinned(0);
            }

            int result = articlesService.post(article);

            if (result > 0) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "信息发布成功");
                response.put("articleId", article.getId());
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(createErrorResponse("信息发布失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("发布信息时发生错误: " + e.getMessage()));
        }
    }

    /**
     * 分页获取信息列表（可按类型筛选：新闻/通知）
     */
    @GetMapping("/get")
    public ResponseEntity<?> getArticles(
            @RequestParam(required = false) Integer type,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            // 实际应用中应该实现分页和类型筛选逻辑
            List<articles> articles = articlesService.get();

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", articles);
            response.put("page", page);
            response.put("size", size);
            response.put("total", articles.size()); // 实际应该查询总记录数
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取信息列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取单条信息详情
     */
    @GetMapping("/get/{articleId}")
    public ResponseEntity<?> getArticleDetail(@PathVariable Long articleId) {
        try {
            if (articleId == null || articleId <= 0) {
                return ResponseEntity.badRequest().body(createErrorResponse("无效的信息ID"));
            }

            articles article = articlesService.getById(articleId);
            if (article == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(createErrorResponse("未找到该信息"));
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", article);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取信息详情失败: " + e.getMessage()));
        }
    }

    /**
     * 修改信息（包括置顶操作）
     */
    @PutMapping("/modify")
    public ResponseEntity<?> modifyArticle(
            @RequestParam Long articleId,
            @RequestBody articles article) {
        try {
            if (articleId == null || articleId <= 0) {
                return ResponseEntity.badRequest().body(createErrorResponse("无效的信息ID"));
            }

            // 1. 查询原文章信息
            articles existingArticle = articlesService.getById(articleId);
            if (existingArticle == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(createErrorResponse("未找到该信息"));
            }

            // 2. 保留原有的 author_id（关键步骤）
            article.setAuthorId(article.getAuthorId() == null ? existingArticle.getAuthorId() : article.getAuthorId());
            article.setType(article.getType() == null ? existingArticle.getType() :  article.getType());
            article.setTitle(article.getTitle() == null ? existingArticle.getTitle() : article.getTitle());
            article.setContent(article.getContent() == null ? existingArticle.getContent() : article.getContent());
            article.setCreatedAt(existingArticle.getCreatedAt());
            article.setIsPinned(existingArticle.getIsPinned());


            // 3. 设置要更新的ID和更新时间
            article.setId(articleId);
            article.setUpdatedAt(LocalDate.now());

            int result = articlesService.modify(article);

            if (result > 0) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "信息更新成功");
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(createErrorResponse("信息更新失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("更新信息时发生错误: " + e.getMessage()));
        }
    }

    /**
     * 删除信息
     */
    @DeleteMapping("/delete")
    public ResponseEntity<?> deleteArticle(@RequestParam Long articleId) {
        try {
            if (articleId == null || articleId <= 0) {
                return ResponseEntity.badRequest().body(createErrorResponse("无效的信息ID"));
            }

            // 检查信息是否存在
            articles existingArticle = articlesService.getById(articleId);
            if (existingArticle == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(createErrorResponse("未找到该信息"));
            }

            int result = articlesService.delete(articleId);

            if (result > 0) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "信息删除成功");
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(createErrorResponse("信息删除失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("删除信息时发生错误: " + e.getMessage()));
        }
    }

    // 辅助方法：创建错误响应
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> error = new HashMap<>();
        error.put("success", false);
        error.put("message", message);
        return error;
    }
}